﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using EngineWindowsApplication1.SDESqlServerConnect;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.esriSystem;
using EngineConsoleApplication1;
using MyEngineExercise.我的扩展;


namespace EngineWindowsApplication1.DataLoader
{
    public partial class DatasetListForm : Form
    {
        private const String SERVER = "PC-201203161034";//服务器名称
        private const String INSTANCE = "esri_sde";//服务名称
        private const String DATABASE = "sde";//数据库名称
        private const String USER = "sde";//用户
        private const String PASSWORD = "222222";//密码
        private const String VERSION = "sde.DEFAULT";//版本

        private SqlServerConnectInfor _sqlServerConnectInfor = null;


        private static LicenseInitializer m_AOLicenseInitializer = new LicenseInitializer();

        private ISpatialReferenceFactory3 _coordinateSystemFactory;//用于创建空间参考

        private IFeatureWorkspace _featureWorkspace = null;//工作空间

        private string _toCreateFeatureClassName = "testFeatureClass";//要创建的FeatureClass的名字



        /// <summary>
        /// 构造函数
        /// </summary>
        public DatasetListForm()
        {
            InitializeComponent();

            _coordinateSystemFactory = new SpatialReferenceEnvironmentClass();
            _sqlServerConnectInfor = new SqlServerConnectInfor(SERVER, INSTANCE, DATABASE, USER, PASSWORD, VERSION);

            _featureWorkspace = (IFeatureWorkspace)_sqlServerConnectInfor.GetWorkspace();//获取featureworkspace

        } 



        /// <summary>
        /// 搜索
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void seaBnt_Click(object sender, EventArgs e)
        {

        }



        /// <summary>
        /// 添加featureclass到数据库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            if (null != _featureWorkspace)
            {
                IFeatureClass featureClass = null;

                //#region 连接sde创建featureclass时，一定不能少了这个
                //设置分辨率
                //ISpatialReferenceResolution pSpatialReferenceResolution = (ISpatialReferenceResolution)spatialReference;
                //pSpatialReferenceResolution.ConstructFromHorizon();
                //#endregion
                featureClass = CreateFeatueClass(_toCreateFeatureClassName, _featureWorkspace);

                if (null != featureClass)
                    MessageBox.Show("创建成功!", "创建失败", MessageBoxButtons.OK, MessageBoxIcon.Information);
                else
                    MessageBox.Show("创建失败!", "创建失败", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }




        /// <summary>
        /// 创建FeatueClass
        /// </summary>
        /// <param name="spatialReference"></param>
        /// <param name="featureClassName"></param>
        /// <param name="featureWorkspace"></param>
        /// <returns></returns>
        private  IFeatureClass CreateFeatueClass( string featureClassName, IFeatureWorkspace featureWorkspace)
        {

            Int32 Prj39Code = (Int32)esriSRProjCS4Type.esriSRProjCS_Xian1980_3_Degree_GK_Zone_39;

            ISpatialReference spatialReference = (ISpatialReference)_coordinateSystemFactory.CreateProjectedCoordinateSystem(Prj39Code);

            #region /**创建InMemory图层并添加到地图窗口中*/
            //IWorkspaceFactory workspaceFactory = new InMemoryWorkspaceFactoryClass();

            //ESRI.ArcGIS.Geodatabase.IWorkspaceName workspaceName = workspaceFactory.Create(String.Empty, "MyInMemWorkspace", null, 0);

            //ESRI.ArcGIS.esriSystem.IName pName = (ESRI.ArcGIS.esriSystem.IName)workspaceName;

            //ESRI.ArcGIS.Geodatabase.IWorkspace inmemWor = (IWorkspace)pName.Open();

            //ESRI.ArcGIS.Geodatabase.IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)inmemWor;

            var fcDescription = (IFeatureClassDescription)new FeatureClassDescriptionClass();
            var ocDescription = (IObjectClassDescription)fcDescription;

            var fields = ocDescription.RequiredFields; // Fields
            var fieldsEdit = (IFieldsEdit)fields;

            #region 创建字段
            IField field = new FieldClass();
            IFieldEdit fieldEdit = (IFieldEdit)field;
            fieldEdit.AliasName_2 = "界址点数";
            fieldEdit.Name_2 = "界址点数";
            fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
            fieldEdit.Precision_2 = 19;
            fieldEdit.Scale_2 = 5;
            fieldsEdit.AddField(field);

            IField field2 = new FieldClass();
            IFieldEdit fieldEdit2 = (IFieldEdit)field2;
            fieldEdit2.AliasName_2 = "地块面积";
            fieldEdit2.Name_2 = "地块面积";
            fieldEdit2.Type_2 = esriFieldType.esriFieldTypeDouble;
            fieldEdit2.Precision_2 = 19;
            fieldEdit2.Scale_2 = 5;
            fieldsEdit.AddField(field2);

            IField field3 = new FieldClass();
            IFieldEdit fieldEdit3 = (IFieldEdit)field3;
            fieldEdit3.AliasName_2 = "地块编号";
            fieldEdit3.Name_2 = "地块编号";
            fieldEdit3.Type_2 = esriFieldType.esriFieldTypeString;
            fieldEdit3.Length_2 = 100;
            fieldsEdit.AddField(field3);

            IField field4 = new FieldClass();
            IFieldEdit fieldEdit4 = (IFieldEdit)field4;
            fieldEdit4.AliasName_2 = "地块名称";
            fieldEdit4.Name_2 = "地块名称";
            fieldEdit4.Type_2 = esriFieldType.esriFieldTypeString;
            fieldEdit4.Length_2 = 100;
            fieldsEdit.AddField(field4);

            IField field5 = new FieldClass();
            IFieldEdit fieldEdit5 = (IFieldEdit)field5;
            fieldEdit5.AliasName_2 = "图形类型";
            fieldEdit5.Name_2 = "图形类型";
            fieldEdit5.Type_2 = esriFieldType.esriFieldTypeString;
            fieldEdit5.Length_2 = 100;
            fieldsEdit.AddField(field5);

            IField field6 = new FieldClass();
            IFieldEdit fieldEdit6 = (IFieldEdit)field6;
            fieldEdit6.AliasName_2 = "图幅号";
            fieldEdit6.Name_2 = "图幅号";
            fieldEdit6.Type_2 = esriFieldType.esriFieldTypeString;
            fieldEdit6.Length_2 = 100;
            fieldsEdit.AddField(field6);

            IField field7 = new FieldClass();
            IFieldEdit fieldEdit7 = (IFieldEdit)field7;
            fieldEdit7.AliasName_2 = "地块用途";
            fieldEdit7.Name_2 = "地块用途";
            fieldEdit7.Type_2 = esriFieldType.esriFieldTypeString;
            fieldEdit7.Length_2 = 100;
            fieldsEdit.AddField(field7);

            IField field8 = new FieldClass();
            IFieldEdit fieldEdit8 = (IFieldEdit)field8;
            fieldEdit8.AliasName_2 = "地类编码";
            fieldEdit8.Name_2 = "地类编码";
            fieldEdit8.Type_2 = esriFieldType.esriFieldTypeString;
            fieldEdit8.Length_2 = 100;
            fieldsEdit.AddField(field8);

            IField field9 = new FieldClass();
            IFieldEdit fieldEdit9 = (IFieldEdit)field9;
            fieldEdit9.AliasName_2 = "描述";
            fieldEdit9.Name_2 = "描述";
            fieldEdit9.Type_2 = esriFieldType.esriFieldTypeString;
            fieldEdit9.Length_2 = 100;
            fieldsEdit.AddField(field9);
            #endregion


            #region 连接sde创建featureclass时，一定不能少了这个
            //设置分辨率
            ISpatialReferenceResolution pSpatialReferenceResolution = (ISpatialReferenceResolution)spatialReference;
            pSpatialReferenceResolution.ConstructFromHorizon();
            #endregion

            int shapeFieldIndex = fields.FindField(fcDescription.ShapeFieldName);
            IField shpField = fields.get_Field(shapeFieldIndex);
            IFieldEdit2 shpFieldEdit = (IFieldEdit2)shpField;
            //shpFieldEdit.GeometryDef_2 
            ESRI.ArcGIS.Geodatabase.IGeometryDef geometryDef = shpField.GeometryDef;
            ESRI.ArcGIS.Geodatabase.IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;

            geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon;
            geometryDefEdit.SpatialReference_2 = spatialReference;
            shpFieldEdit.GeometryDef_2 = geometryDefEdit;

            //检查字段是否符合
            IFieldChecker fieldChecker = new FieldCheckerClass();
            IEnumFieldError enumFieldError = null;
            IFields validatedFields = null;
            //fieldChecker.ValidateWorkspace = inmemWor;
            fieldChecker.ValidateWorkspace = (IWorkspace)featureWorkspace;
            // 检查
            fieldChecker.Validate(fields, out enumFieldError, out validatedFields);

            if (null != enumFieldError)
            {
                enumFieldError.Reset();
                IFieldError fieldError = null;
                while ((fieldError = enumFieldError.Next()) != null)
                {
                    MessageBox.Show("创建字段失败！:\n" + fieldError.FieldError.ToString());
                }

            }
            if (null != enumFieldError) return null;

            IFeatureClass featureClass = null;
            try
            {
                featureClass = featureWorkspace.CreateFeatureClass(
                            featureClassName, validatedFields,//validatedFields!=null?validatedFields:fields, 
                            ocDescription.InstanceCLSID,
                            ocDescription.ClassExtensionCLSID,
                            esriFeatureType.esriFTSimple,
                            fcDescription.ShapeFieldName, String.Empty);

                //修改别名
                IClassSchemaEdit classSchemaEdit = (IClassSchemaEdit)featureClass;
                classSchemaEdit.AlterAliasName("sde要素类");
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            

            #endregion //#!
            return featureClass;
        }





        /// <summary>
        /// 添加记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            IFeatureClass insertFeatureClass = null;
            IFeatureClass featureClass = null;
            OpenFileDialog openFileDialog_insert = new OpenFileDialog();
            openFileDialog_insert.Title = "选择一个featureclass,将该featureclass的shape字段插入";
            openFileDialog_insert.Filter = "shape file|*.shp";
            if (openFileDialog_insert.ShowDialog(this) != DialogResult.Cancel)
            {
                insertFeatureClass = MyAeMethods.Instance.NewFeatureClass(openFileDialog_insert.FileName);
                if (null != insertFeatureClass)
                {
                    featureClass = _featureWorkspace.OpenFeatureClass(_toCreateFeatureClassName);
                    
                    IGeometry geometry = null;

                    int shapeFieldIndex = insertFeatureClass.Fields.FindField(insertFeatureClass.ShapeFieldName);
                    IFeatureCursor featureCursor = insertFeatureClass.Search(null, true);
                    IFeature feature = null;
                    if ((feature = featureCursor.NextFeature()) != null)
                    {
                        geometry = (IGeometry)feature.get_Value(shapeFieldIndex);
                    }

                    IFeatureBuffer featureBuffer = featureClass.CreateFeatureBuffer();
                    featureBuffer.Shape = geometry;

                    IFeatureCursor insertFeatureCursor = null;
                    insertFeatureCursor = featureClass.Insert(true);
                    insertFeatureCursor.InsertFeature(featureBuffer);
                }
            }

        }



        
    }
}
